#! /bin/bash

# 升级podspec文件version
function update_podspec_version() {
    local file_path=$1

    # search s.version line
    version_line=`sed -n "/s.version /p" ${file_path}`

    # get last build number
    version=`echo ${version_line} | grep -Eo "\d+\.\d+\.\d+"`
    #echo ${VERSION}

    # split version
    X=0, Y=0, Z=0
    X=`echo ${version} | awk -F'.' '{print $1}'`
    Y=`echo ${version} | awk -F'.' '{print $2}'`
    Z=`echo ${version} | awk -F'.' '{print $3}'`

    # 替换原文件中的版本号
    buildnumber=$((Z+1))
    sed -i ".bak" "s/\(s[.]version[  ]*\=[  ]*[\'\"][0-9]\.[0-9]*\.\)\([0-9]*\)\([\'\"]\)/\1${buildnumber}\3/g" ${file_path}

    # 删除bak
    bak_file="${file_path}.bak"
    rm ${bak_file}

    new_version="$((X)).$((Y)).${buildnumber}"
    echo "update version to ${new_version}"
    commit_version ${new_version}
}

# 查找podspec文件
function find_podspec_file() {
    current_dir=`pwd`
    podspec_file=`fd ".podspec$"`
    if [ ! -n "${podspec_file}" ]; then
        echo
    else
        echo ${current_dir}/${podspec_file}
    fi
}

# 提交commit
function commit_version() {
    echo `git commit -am "chore:update version to $1"`
}

podspec_file=$(find_podspec_file)

if [ ! ${podspec_file} ]; then
    echo "not find podspec file."
else
    update_podspec_version ${podspec_file}
fi
